package com.anlogic.sdk.utils.loggers;

import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MenuDetectEvent;
import org.eclipse.swt.events.MenuDetectListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.ui.console.IOConsole;
import org.eclipse.ui.part.ViewPart;

public class LoggerConsoleView extends ViewPart {
	private IOConsole logConsole;
	
	private LoggerConsoleViewer conoleViewer;

	@Override
	public void createPartControl(Composite parent) {
		this.logConsole = LoggerConsoleAppender.getLogConsole();
		this.conoleViewer = new LoggerConsoleViewer(parent, this.logConsole);
		this.conoleViewer.setEditable(false);
		GridDataFactory.fillDefaults().grab(true, true).applyTo(this.conoleViewer.getControl());
		
		createContextMenu();
	}

	@Override
	public void setFocus() {
		this.conoleViewer.getControl().setFocus();
	}

	public void clearConsole() {
		this.logConsole.clearConsole();
	}
	
    private void createContextMenu() {
    	Menu menu = new Menu(this.conoleViewer.getControl());
        
        MenuItem clearItem = new MenuItem(menu, SWT.PUSH);
        clearItem.setText("Clear");
        clearItem.addListener(SWT.Selection, e -> clearConsole());

        this.conoleViewer.getControl().setMenu(menu);
        
        this.conoleViewer.getControl().addMenuDetectListener(new MenuDetectListener() {
            @Override
            public void menuDetected(MenuDetectEvent e) {
            	menu.setVisible(true);
            }
        });
    }
}
